package find

import (
	"errors"
	"net"
)

type Access struct {
	Ipv4Search *IpInfo
	Ipv6Search *IpInfoV6
}

func (a *Access) Get(ipStr string) (string, error) {
	var ip net.IP
	if ip = net.ParseIP(ipStr); ip == nil {
		return "", errors.New("invalid IP")
	}
	if ip.To4() != nil {
		res, err := a.Ipv4Search.GetByNet(ip)
		if err != nil {
			return "", err
		}
		return res, nil
	} else if ip.To16() != nil {
		res, err := a.Ipv6Search.GetByNet(ip)
		if err != nil {
			return "", err
		}
		return res, nil
	} else {
		return "", errors.New("invalid ip")
	}
}

func GetAccess(ipv4File, ipv6File string) (*Access, error) {
	ipv4Search, err := GetObjectV4LocationMemory(ipv4File)
	if err != nil {
		return nil, err
	}
	ipv6Search, err := GetObjectV6Memory(ipv6File)
	if err != nil {
		return nil, err
	}
	acc := Access{
		Ipv4Search: ipv4Search,
		Ipv6Search: ipv6Search,
	}
	return &acc, nil
}
